package com.minicat.servlet;

import com.utils.HttpProtocolMocker;
import com.utils.StaticResourceUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author liangzj
 * @date 2021/3/28 15:38
 */
public class Response {

    private OutputStream outputStream;

    /**
     * @param path 根据path获取静态资源的绝对路径
     */
    public void outputHtml(String path) throws IOException {
        String absolutePath = StaticResourceUtil.getAbsolutePath(path);

        File file = new File(absolutePath);
        // 获取要输出的静态资源，否则提示404
        if (file.exists()) {
            FileInputStream fileInputStream = new FileInputStream(file);
            StaticResourceUtil.outputStaticResource(fileInputStream, outputStream);
        } else {
            outputContent(HttpProtocolMocker.mockHttpHeader404());
        }
    }

    /**
     * 输出文本
     *
     * @param content
     */
    public void outputContent(String content) throws IOException {
        outputStream.write(content.getBytes(StandardCharsets.UTF_8));
    }

    public void outputHttpContent(String content) throws IOException {
        String httpHeader200 = HttpProtocolMocker.mockHttpHeader200(content.getBytes(StandardCharsets.UTF_8).length);
        outputStream.write(httpHeader200.getBytes(StandardCharsets.UTF_8));
        outputStream.write(content.getBytes(StandardCharsets.UTF_8));
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
}
